package com.wt.demo.threadtest.niosocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.LockSupport;

/**
 * @description
 * @author: wangtao
 * @date:11:35 2018/6/13
 * @email:tao8.wang@changhong.com
 */
public class HaveySocketClient {

    private static ExecutorService exec = Executors.newCachedThreadPool();
    private static long SLEEP_TIME = 1000*1000*1000;

    static class ECHOClient implements Runnable {
        Socket client;
        PrintWriter writer;
        BufferedReader br;

        @Override
        public void run() {
            try {
                client = new Socket();
                client.connect(new InetSocketAddress("127.0.0.1", 8000));
                writer = new PrintWriter(client.getOutputStream(), true);
                for (int i = 0; i < 6; i++) {
                    LockSupport.parkNanos(SLEEP_TIME);
                    writer.write(i + "");
                }
                writer.println();
                writer.flush();

                br = new BufferedReader(new InputStreamReader(client.getInputStream()));
                System.out.println("from server: " + br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (writer != null) {
                        writer.close();
                    }
                    if (br != null) {
                        br.close();
                    }
                    if (client != null) {
                        client.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        ECHOClient client = new ECHOClient();
        for (int i = 0; i < 10; i++) {
            exec.submit(new ECHOClient());
        }
    }
}
